from flask import current_app, session, request, jsonify, g
from flask_sqlalchemy import Pagination

from info.constants import CLICK_RANK_MAX_NEWS, HOME_PAGE_MAX_NEWS
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET, error_map
from . import home_blu
from flask import render_template



@home_blu.route('/favicon.ico')
def get_favicon():

    return current_app.send_static_file("news/favicon.ico")

@home_blu.route('/')
@user_login_data
def index():

    # 取出数据库的新闻信息按点击量
    news_list = None  #type:list[News]
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS).all()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg=error_map[RET.DBERR])
    # 取分类数据
    try:
        categories = Category.query.all()  #type:list[Category]
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg=error_map[RET.DBERR])
    user = g.user.to_dict() if g.user else None
    return render_template("news/index.html", user=user, news_list=news_list, categories=categories)

@home_blu.route('/get_news_list')
def get_news_list():
    # 获取参数
    cid = request.args.get("cid")
    cur_page = request.args.get("cur_page")
    per_count = request.args.get("per_count",HOME_PAGE_MAX_NEWS)
    # 校验参数完整性
    if not all([cid,cur_page]):
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])
    # 类型转换
    try:
        cid = int(cid)
        cur_page = int(cur_page)
        per_count = int(per_count)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    filter_list = [News.status ==0]
    if cid != 1:
        filter_list.append(News.category_id==cid)
    # 取数据
    try:
        pn = News.query.filter(*filter_list).order_by(News.create_time.desc()).\
            paginate(cur_page,per_count) #type:Pagination
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg=error_map[RET.DBERR])
    # 转换成jsonify可以转换成json的格式
    data = {
        "news_list":[news.to_dict()for news in pn.items],
        "total_page":pn.pages
    }

    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK],data=data)